<template>
  <div class="main">
    <div class="box">
      <!-- <ul :class="{ loading: isLoading }"> -->
      <ul v-loading="isLoading">
        <li v-for="item in list" :key="item.id" class="news">
          <div class="left">
            <div class="title">{{ item.title }}</div>
            <div class="info">
              <span>{{ item.source }}</span>
              <span>{{ item.time }}</span>
            </div>
          </div>

          <div class="right">
            <img :src="item.img" alt="">
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
// 安装axios =>  yarn add axios
import axios from 'axios'

// 接口地址：http://hmajax.itheima.net/api/news
// 请求方式：get
export default {
  directives: {
    loading: {
      // 只会执行一次，当数据发生变化不会执行，会执行update
      inserted(el, binding) {
        if (binding.value) {
          // 给el添加loading类名
          el.classList.add('loading')
        } else {
          // 给el移除loading类名
          el.classList.remove('loading')
        }
      },
      update(el, binding) {
        const methodName = binding.value ? 'add' : 'remove'
        el.classList[methodName]('loading')

        // if (binding.value) {
        //   // 给el添加loading类名
        //   el.classList.add('loading')
        // } else {
        //   // 给el移除loading类名
        //   el.classList.remove('loading')
        // }

        // classList = {
        //   add: function () {},
        //   remove : function () {}
        // }
      }
    }
  },
  data () {
    return {
      isLoading: false,
      list: []
    }
  },
  async created () {

    // 请求前，转起来
    this.isLoading = true

    // 1. 发送请求获取数据
    const res = await axios.get('http://hmajax.itheima.net/api/news')
    
    setTimeout(() => {
      // 2. 更新到 list 中
      this.list = res.data.data

      // 请求完后，停止loading效果
      this.isLoading = false

    }, 2000)
  }
}
</script>

<style>
/* 伪类 - 蒙层效果 */
.loading:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff url('./loading.gif') no-repeat center;
}

/* .box2 {
  width: 400px;
  height: 400px;
  border: 2px solid #000;
  position: relative;
} */

.box {
  width: 800px;
  min-height: 500px;
  border: 3px solid orange;
  border-radius: 5px;
  position: relative;
}
.news {
  display: flex;
  height: 120px;
  width: 600px;
  margin: 0 auto;
  padding: 20px 0;
  cursor: pointer;
}
.news .left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-right: 10px;
}
.news .left .title {
  font-size: 20px;
}
.news .left .info {
  color: #999999;
}
.news .left .info span {
  margin-right: 20px;
}
.news .right {
  width: 160px;
  height: 120px;
}
.news .right img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>